#include "CComponentBridge.h"

#include <QAction>
#include <QApplication>
#include <QMenu>
#include <QSystemTrayIcon>

CComponentBridge* CComponentBridge::s_pComponentBridge = nullptr;

CComponentBridge::CComponentBridge(QObject* object)
    : QObject(object)
{
    m_pTrayIcon = nullptr;
    m_pTrayMenu = nullptr;
}

CComponentBridge::~CComponentBridge()
{
    if (m_pTrayIcon) {
        delete m_pTrayIcon;
        m_pTrayIcon = nullptr;
    }
}

void CComponentBridge::InitSystemTrayIcon(QWidget* parent)
{
    // 创建系统托盘图标对象
    m_pTrayIcon = new QSystemTrayIcon(QIcon(":/resource/icon.ico"), parent);

    // 创建菜单
    m_pTrayMenu = new QMenu(parent);

    // 创建菜单项动作
    m_pQuitAction = new QAction("退出     ", parent);
    connect(m_pQuitAction, &QAction::triggered, [this]() {
        emit this->signalTrayActionExit();
    });

    // 将动作添加到菜单
    m_pTrayMenu->addAction(m_pQuitAction);

    // 将菜单设置给系统托盘图标
    m_pTrayIcon->setContextMenu(m_pTrayMenu);

    // 显示系统托盘图标
    m_pTrayIcon->show();
}

QSystemTrayIcon* CComponentBridge::GetTrayIcon()
{
    return m_pTrayIcon;
}

void CComponentBridge::ShowSystemMessage(const QString& title, const QString& msg, QSystemTrayIcon::MessageIcon icon, int msecs)
{
    m_pTrayIcon->showMessage(title, msg, icon, msecs);
}

void CComponentBridge::SetSystemIconToolTip(const QString& msg)
{
    m_pTrayIcon->setToolTip(msg);
}

CComponentBridge* CComponentBridge::GetInstance()
{
    if (s_pComponentBridge == nullptr) {
        s_pComponentBridge = new CComponentBridge();
    }
    return s_pComponentBridge;
}

bool CComponentBridge::ReleaseInstance()
{
    if (s_pComponentBridge != nullptr) {
        delete s_pComponentBridge;
        s_pComponentBridge = nullptr;
        return true;
    }

    return false;
}
